<template>
  <view class="page-container">
    <!-- 顶部导航 - 固定 -->
    <view class="fixed-header">
      <S1Header title="订单详情" :on-back="onBack" />
    </view>

    <!-- 可滚动内容区域 -->
    <scroll-view scroll-y class="scrollable-content">
      <!-- 订单头部信息 -->
      <view class="order-header mb-2">
        <view class="px-4 pb-2 pt-3">
          <view class="relative flex justify-between">
            <text class="text-black">
              票号: {{ orderInfo.piao_num }}
            </text>
            <view class="dangban-tag">
              <text class="text-xs text-green-500">
                当班
              </text>
            </view>
          </view>
          <view class="mt-3">
            <text class="text-lg text-white font-bold">
              {{
                orderInfo.buyer
              }}
            </text>
          </view>
          <view class="mt-3 flex justify-between text-xs text-white">
            <text>开单: {{ orderInfo.openTime }} </text>
            <text>收银: {{ orderInfo.payTime }}</text>
          </view>
        </view>
      </view>

      <!-- 订单明细标题 -->
      <view v-if="orderInfo.orderType !== '白条录入'" class="flex items-center justify-between bg-white px-4 py-3">
        <text class="text-base font-bold">
          订单明细
        </text>
        <text class="text-sm text-green-500">
          (已结清 应收:
          <text class="text-green-500">
            {{ orderInfo.totalAmount }}
          </text> 实收:
          <text class="text-green-500">
            {{ orderInfo.actualAmount }}
          </text>)
        </text>
      </view>

      <!-- 商品表格 - 当orderType不是白条录入时显示 -->
      <view v-if="orderInfo.orderType !== '白条录入'" class="order-table">
        <!-- 表头 -->
        <view class="table-header">
          <view class="th goods-info">
            货品信息
          </view>
          <view class="th quantity">
            数量
          </view>
          <view class="th price">
            价格
          </view>
          <view class="th subtotal">
            小计
          </view>
        </view>

        <!-- 商品行 -->
        <view v-for="(item, index) in goodsList" :key="index" class="table-row">
          <view class="td goods-info">
            <view class="flex items-start">
              <text class="mr-1">
                {{ index + 1 }}.
              </text>
              <view class="flex flex-col">
                <text>{{ item.name }}</text>
                <text
                  class="market-tag green-market"
                >
                  {{ item.tag }}
                </text>
              </view>
            </view>
          </view>
          <view class="td quantity">
            <view class="flex flex-col items-center">
              <text>{{ item.pieces }}</text>
            </view>
          </view>
          <view class="td price">
            {{ item.price }}
          </view>
          <view class="td subtotal">
            {{ item.subtotal }}
          </view>
        </view>
      </view>

      <!-- 白条图片 - 当orderType是白条录入时显示 -->
      <view v-if="orderInfo.orderType === '白条录入' && orderInfo.imageUrl" class="white-note-img bg-white p-4">
        <image :src="orderInfo.imageUrl" mode="aspectFit" class="white-note-image rounded-lg" @tap="previewImage" />
      </view>

      <!-- 操作人信息 -->
      <view class="operator-info">
        <view class="px-4 py-1">
          <text>开单员: {{ orderInfo.opener }}</text>
        </view>
        <view class="px-4 py-1">
          <text>收银员: {{ orderInfo.cashier }}</text>
        </view>
      </view>

      <!-- 订单操作记录 -->
      <view class="operation-block mt-2">
        <!-- 标题 -->
        <view class="record-header flex items-center px-4 py-3">
          <text class="text-base font-bold">
            订单操作记录
          </text>
        </view>

        <!-- 操作记录列表 -->
        <view v-for="(record, index) in operationRecords" :key="index" class="record-item">
          <!-- 左侧操作类型标记 -->
          <view class="record-type-indicator" :class="getTypeClass(record.originalData?.type)" />

          <view class="record-content">
            <view class="flex justify-between">
              <text class="record-type">
                {{ record.type }}
              </text>
              <!-- 右侧金额信息 -->
              <view class="flex flex-col items-end">
                <!-- 开单收银、开单赊欠、恢复订单、改单 -->
                <template v-if="[1, 2, 4, 7].includes(record.originalData?.type)">
                  <text class="text-green-500 font-medium">
                    应收: {{ record.total_price }}元
                  </text>
                  <text v-if="record.status !== 0" class="text-green-500 font-medium">
                    实收: {{ record.shishou }}元
                  </text>
                  <text v-if="record.status === 0" class="text-green-500 font-medium">
                    下欠: {{ record.total_price
                    }}元
                  </text>
                </template>

                <!-- 操作还款 -->
                <template v-else-if="record.originalData?.type === 5">
                  <text class="text-green-500 font-medium">
                    还款金额: {{ record.amount }}
                  </text>
                </template>

                <!-- 作废订单 -->
                <template v-else-if="record.originalData?.type === 3">
                  <text class="text-red-500 font-medium">
                    作废金额: {{ record.total_price }}元
                  </text>
                </template>

                <!-- 其他情况 -->
                <template v-else>
                  <text class="text-green-500 font-medium">
                    {{ record.amount }}
                  </text>
                </template>
              </view>
            </view>

            <!-- 操作时间和操作人 -->
            <view class="mt-1 flex">
              <view class="time-operator-tag">
                <text class="text-xs">
                  {{ record.time }} {{ record.operator }}
                </text>
              </view>
            </view>

            <!-- 添加支付方式显示 -->
            <view v-if="record.paymentMethod" class="payment-method-info mt-2">
              <text class="text-xs">
                支付方式: {{ record.paymentMethod }}
              </text>
            </view>
          </view>
        </view>
      </view>

      <!-- 备注区域 -->
      <view v-if="orderInfo.orderType !== '白条录入'" class="remark-area">
        <textarea v-model="remarkText" class="remark-textarea" placeholder="备注一下" auto-height />
      </view>

      <!-- 底部安全区域 -->
      <view class="safe-bottom-area" />
    </scroll-view>

    <!-- 底部操作栏 - 固定 -->
    <view class="fixed-bottom-bar">
      <view class="buttons-group">
        <button class="cancel-btn" @tap="onCancelOrder">
          作废
        </button>
        <button v-if="orderInfo.orderType !== '白条赊欠'" class="edit-btn" @tap="onEditOrder">
          改单
        </button>
        <button v-if="orderInfo.orderType !== '白条录入'" class="repay-btn" @tap="onRepayOrder">
          操作还款
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { getOrderDetailData, updateOrderData, zuofeiOrderData } from '@/api/order';
import S1Header from '@/components/S1Header.vue';

// 页面数据
const orderNo = ref<string>('00548');
const orderInfo = ref<any>({});
const originalOrderData = ref<any>(null); // 添加存储原始订单数据的ref

// 备注文本
const remarkText = ref('');

// 商品列表
const goodsList = ref([
  {
    name: '上海青',
    tag: '海淀市场',
    pieces: '163件',
    weight: '9999公斤',
    price: '18/件',
    subtotal: '80',
  },
  {
    name: '毛白菜',
    tag: '天通市场',
    pieces: '163件',
    weight: '',
    price: '18/件',
    subtotal: '80',
  },
]);

// 操作记录
const operationRecords = ref<any[]>([]);

// 导航返回
const onBack = () => uni.navigateBack();

// 作废订单
const onCancelOrder = () => {
  uni.showModal({
    title: '确认作废',
    content: '确定要作废此订单吗？',
    success(res) {
      if (res.confirm) {
        // 检查订单信息是否存在
        if (!originalOrderData.value || !originalOrderData.value.id) {
          uni.showToast({
            title: '订单数据不存在',
            icon: 'none',
          });
          return;
        }

        // 显示加载提示
        uni.showLoading({
          title: '处理中...',
        });

        // 调用作废订单API，zuofei参数固定为1
        zuofeiOrderData({ id: originalOrderData.value.id, zuofei: 1 }).then((res) => {
          uni.hideLoading();

          if (res && res.code === 200) {
            uni.showToast({
              title: '作废成功',
              icon: 'success',
            });

            // 作废成功后返回上一页
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          }
          else {
            uni.showToast({
              title: res?.msg || '作废失败',
              icon: 'none',
            });
          }
        }).catch((err) => {
          uni.hideLoading();
          uni.showToast({
            title: '作废失败，请重试',
            icon: 'none',
          });
          console.error('作废订单失败:', err);
        });
      }
    },
  });
};

// 改单
const onEditOrder = () => {
  // 检查订单信息是否存在
  if (!orderInfo.value || !originalOrderData.value || !originalOrderData.value.id) {
    uni.showToast({
      title: '订单数据不存在',
      icon: 'none',
    });
    return;
  }

  // 显示加载提示
  uni.showLoading({
    title: '处理中...',
  });

  // 调用改单接口
  updateOrderData({ id: originalOrderData.value.id }).then((res) => {
    uni.hideLoading();

    if (res && res.code === 200) {
      uni.showToast({
        title: '改单成功',
        icon: 'success',
      });

      // 成功后跳转到购物车页面，模仿handleBatchTakeOrder的跳转逻辑
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/cart/index',
        });
      }, 1500);
    }
    else {
      uni.showToast({
        title: res?.msg || '改单失败',
        icon: 'none',
      });
    }
  }).catch((err) => {
    uni.hideLoading();
    uni.showToast({
      title: '改单失败，请重试',
      icon: 'none',
    });
    console.error('改单失败:', err);
  });
};

// 预览图片
const previewImage = () => {
  if (orderInfo.value.imageUrl) {
    uni.previewImage({
      urls: [orderInfo.value.imageUrl],
      current: orderInfo.value.imageUrl,
    });
  }
};

// 根据操作类型获取样式类名
const getTypeClass = (type: number | undefined) => {
  if (!type) return 'type-default';

  switch (type) {
    case 1: return 'type-pay'; // 开单收银
    case 2: return 'type-credit'; // 开单赊欠
    case 3: return 'type-cancel'; // 作废订单
    case 4: return 'type-restore'; // 恢复订单
    case 5: return 'type-repay'; // 操作还款
    case 6: return 'type-undo'; // 撤销还款
    case 7: return 'type-edit'; // 改单
    case 22: return 'type-owe'; // 打欠
    default: return 'type-default';
  }
};

// 获取页面参数，加载订单详情
onMounted(() => {
  // 在onMounted中什么都不做
});

// 获取订单操作记录
const fetchOrderOperationRecords = (orderId: number, piaoNum: string) => {
  getOrderDetailData({ order_id: orderId, piao_num: piaoNum }).then((res) => {
    if (res && res.code === 200 && res.data && res.data.length > 0) {
      // 将API返回的数据转换为操作记录格式
      operationRecords.value = res.data.map((item: any) => {
        // 根据type确定操作类型
        let typeText = '其他操作';
        switch (item.type) {
          case 1:
            typeText = '开单收银';
            break;
          case 2:
            typeText = '开单赊欠';
            break;
          case 3:
            typeText = '作废订单';
            break;
          case 4:
            typeText = '恢复订单';
            break;
          case 5:
            typeText = '操作还款';
            break;
          case 6:
            typeText = '撤销还款';
            break;
          case 7:
            typeText = '改单';
            break;
          case 22:
            typeText = '打欠';
            break;
        }

        // 构建金额显示
        let amountDisplay = '';

        if (item.type === 1 || item.type === 2 || item.type === 4 || item.type === 7) {
          // 开单收银、开单赊欠、恢复订单、改单
          if (item.status !== 0) {
            amountDisplay = `${item.shishou || 0}元`;
          }
          else {
            amountDisplay = `${item.total_price || 0}元`;
          }
        }
        else if (item.type === 3) {
          // 作废订单
          amountDisplay = `${item.total_price || 0}元`;
        }
        else if (item.type === 5 || item.type === 6) {
          // 操作还款、撤销还款
          amountDisplay = `${item.money || 0}元`;
        }
        else if (item.type === 22) {
          // 打欠
          amountDisplay = `${item.money || 0}元`;
        }

        // 构建支付方式描述
        let paymentMethod = '';
        if ((item.type === 1 || item.type === 5) && item.status !== 0) {
          const methods = [];
          if (item.cash_num > 0) methods.push(`现金${item.cash_num}元`);
          if (item.wepay_num > 0) methods.push(`微信${item.wepay_num}元`);
          if (item.alipay_num > 0) methods.push(`支付宝${item.alipay_num}元`);
          if (item.union_num > 0) methods.push(`银联${item.union_num}元`);
          if (item.other_num > 0) methods.push(`其他${item.other_num}元`);

          paymentMethod = methods.join('，');
        }

        return {
          type: typeText,
          amount: amountDisplay,
          time: item.time || '',
          operator: item.user?.name || '',
          paymentMethod,
          status: item.status,
          total_price: item.total_price,
          shishou: item.shishou,
          originalData: item, // 保存原始数据以备需要
        };
      });
    }
  }).catch((err) => {
    console.error('获取订单操作记录失败:', err);
  });
};

// 页面加载时获取参数
onLoad((options: any) => {
  console.log('页面参数:', options);

  // 从缓存中获取完整的订单数据
  const orderData = uni.getStorageSync('currentOrderDetail');
  console.log('完整订单数据:', orderData);

  if (orderData) {
    // 保存原始订单数据
    originalOrderData.value = orderData;

    // 更新订单号
    orderNo.value = orderData.order_num || orderData.id?.toString() || '';

    // 更新订单信息
    orderInfo.value = {
      openTime: orderData.add_time || '',
      payTime: orderData.pay_time || orderData.add_time || '',
      totalAmount: orderData.total_price?.toString() || '0',
      actualAmount: orderData.shishou?.toString() || '0',
      status: orderData.status === 0 ? '未结清' : '已结清',
      buyer: orderData.maijia || orderData.maijia_name || '',
      opener: orderData.user?.name || '',
      cashier: orderData.user?.name || '',
      orderType: orderData.order_type || '',
      imageUrl: orderData.imageUrl || '',
      piao_num: orderData.piao_num || '',
    };

    // 处理商品列表
    if (orderData.order_detail && orderData.order_detail.length > 0) {
      goodsList.value = orderData.order_detail.map((item: any) => {
        return {
          name: item.goods_name || '',
          tag: `${item.num_multiple}${item.unit} = ${item.weight_multiple}${item.mini_type}`,
          pieces: item.mini_type === '公斤' ? `${item.weight}${item.unit}` : `${item.weight}${item.unit}`,
          weight: item.mini_type === '公斤' ? `${item.weight}公斤` : '',
          price: item.price ? `${item.price}/${item.unit}` : '',
          subtotal: item.goods_price?.toString() || '0',
        };
      });
    }
    else {
      goodsList.value = [];
    }

    // 设置备注
    remarkText.value = orderData.notes || '';

    // 如果有订单ID和票号，获取订单操作记录
    if (orderData.id && orderData.piao_num) {
      fetchOrderOperationRecords(orderData.id, orderData.piao_num);
    }

    // 删除缓存
    uni.removeStorageSync('currentOrderDetail');
  }
});

// 操作还款
const onRepayOrder = () => {
  // 检查订单信息是否存在
  if (!orderInfo.value || !orderNo.value || !originalOrderData.value) {
    uni.showToast({
      title: '订单数据不存在',
      icon: 'none',
    });
    return;
  }

  // 使用保存的原始订单数据
  const orderData = originalOrderData.value;

  // 准备还款数据，根据creditRepayment页面需要的参数
  const repayData = {
    orderIds: [Number.parseInt(orderNo.value)], // 订单ID数组
    maijia_id: orderData.maijia_id || 0, // 买家ID
    totalDebt: Number.parseFloat(orderInfo.value.totalAmount) || 0, // 欠款总额
  };

  // 将数据保存到本地存储
  uni.setStorageSync('repaymentData', repayData);

  // 跳转到还款页面
  uni.navigateTo({
    url: `/pages/common/creditRepayment/index`,
  });
};
</script>

<style scoped lang="scss">
.page-container {
  width: 371px;
  height: 100vh;
  margin: 0 auto;
  background-color: #f5f5f5;
  position: relative;
}

/* 固定头部 */
.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  width: 371px;
  margin: 0 auto;
  z-index: 100;
  background-color: #fff;
}

/* 可滚动内容区域 */
.scrollable-content {
  height: 100vh;
  padding-top: 80px;
  /* 顶部导航栏高度 */
  padding-bottom: 68px;
  /* 底部操作栏高度 */
  box-sizing: border-box;
}

/* 底部安全区域 */
.safe-bottom-area {
  height: 20px;
}

/* 固定底部 */
.fixed-bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  width: 371px;
  margin: 0 auto;
  background: white;
  box-shadow: 0 -2px 6px rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.order-header {
  width: 100%;
  background: #43cf7c;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.dangban-tag {
  position: absolute;
  top: -8px;
  right: -8px;
  background-color: white;
  padding: 2px 8px;
  border-radius: 4px;
}

/* 订单表格样式 */
.order-table {
  background: white;
  border: 1px solid #e5e7eb;
  border-collapse: collapse;
  width: 100%;
}

.table-header {
  display: flex;
  background-color: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
  color: #6b7280;
  font-size: 14px;
}

.table-row {
  display: flex;
  border-bottom: 1px solid #e5e7eb;
}

.th,
.td {
  padding: 10px;
  text-align: center;
  white-space: nowrap;
  overflow: visible;
}

.goods-info {
  width: 34%;
  text-align: left;
}

.quantity {
  width: 33%;
}

.price {
  width: 16%;
}

.subtotal {
  width: 17%;
}

.market-tag {
  display: inline-block;
  padding: 2px 4px;
  border-radius: 2px;
  font-size: 12px;
  margin-top: 4px;
}

.green-market {
  background-color: rgba(52, 211, 153, 0.2);
  color: #0f766e;
}

.yellow-market {
  background-color: rgba(251, 191, 36, 0.2);
  color: #92400e;
}

.operator-info {
  background: white;
  border-bottom: 1px solid #e5e7eb;
  padding: 5px 0;
}

.operation-block {
  background: white;
  border-radius: 4px;
}

.record-header {
  border-bottom: 1px solid #eee;
}

.record-item {
  position: relative;
  padding: 12px 16px 12px 24px;
  margin: 0;
  border-bottom: 1px solid #eee;
  display: flex;
}

.record-type-indicator {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  width: 3px;
  height: 70%;
  border-radius: 2px;
}

.record-content {
  flex: 1;
}

.record-type {
  font-weight: 500;
  font-size: 15px;
}

.time-operator-tag {
  display: inline-block;
  padding: 2px 0;
  color: #888;
}

.payment-method-info {
  padding: 4px 0;
  color: #0f766e;
}

/* 操作类型颜色 */
.type-pay {
  background-color: #43cf7c;
}

.type-credit {
  background-color: #fbbf24;
}

.type-cancel {
  background-color: #ef4444;
}

.type-restore {
  background-color: #3b82f6;
}

.type-repay {
  background-color: #8b5cf6;
}

.type-undo {
  background-color: #ec4899;
}

.type-edit {
  background-color: #f97316;
}

.type-owe {
  background-color: #64748b;
}

.type-default {
  background-color: #9ca3af;
}

/* 备注区域 */
.remark-area {
  margin-top: 12px;
  background-color: #f0f9ff;
  border-radius: 4px;
  padding: 12px;
  height: 100px;
}

.remark-textarea {
  width: 100%;
  height: 100%;
  background: transparent;
  border: none;
  font-size: 14px;
  color: #333;
  padding: 0;
}

/* 白条图片样式 */
.white-note-img {
  width: 100%;
  margin-bottom: 10px;
  overflow: hidden;
}

.white-note-image {

  object-fit: contain;
  display: block;
}

/* 底部操作栏 */
.bottom-action-bar {
  display: none;
  /* 隐藏原底部栏 */
}

.buttons-group {
  display: flex;
  padding: 8px;
  width: 100%;
}

.cancel-btn,
.edit-btn,
.repay-btn {
  flex: 1;
  height: 40px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cancel-btn {
  margin-right: 6px;
  background-color: white;
  color: #f56565;
  border: 1px solid #f56565;
}

.edit-btn {
  margin-right: 6px;
  background-color: #f97316;
  color: white;
}

.repay-btn {
  background-color: #43cf7c;
  color: white;
}
</style>
